package com.xcms.test.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.ArrayList;
import java.util.List;

public class OnlineListener implements  HttpSessionAttributeListener {
    static int num=0;
    // Public constructor is required by servlet spec
    public OnlineListener() {
    }

    public void attributeAdded(HttpSessionBindingEvent e) {     //属性的监听
      /* This method is called when an attribute 
         is added to a session.
      */

        ServletContext context=e.getSession().getServletContext();
        List<String> users=(List<String>)context.getAttribute("users");
        if(users==null){
            users=new ArrayList<String>();
        }
        String attrname=e.getName();
        if(attrname.equals("username")){
            users.add((String)e.getSession().getAttribute("username"));
            context.setAttribute("user",users);
            System.out.println("用户登录成功");
            context.setAttribute("num",users.size());
            System.out.println("当前在线人数为"+users.size());
        }
    }

    public void attributeRemoved(HttpSessionBindingEvent e) {

        System.out.println("用户下线成功");
        ServletContext context=e.getSession().getServletContext();
        List<String> users=(List<String>)context.getAttribute("users");

        String attrname=e.getName();
        if(attrname.equals("username")){
            users.remove((String)e.getSession().getAttribute("username"));
            context.setAttribute("user",users);
            context.setAttribute("num",users.size());
            System.out.println("当前人数减少为"+users.size());
        }
    }

    public void attributeReplaced(HttpSessionBindingEvent sbe) {
      /* This method is invoked when an attribute
         is replaced in a session.
      */
    }
}
